export default class WebSocketService {
  constructor(url) {
    this.url = url; // WebSocket 服务器地址
    this.socket = null; // WebSocket 实例
    this.isConnected = false; // 连接状态
    this.eventHandlers = {}; // 存储事件回调函数
  }

  // 建立连接
  connect() {
    if (this.isConnected) return; // 如果已连接，直接返回

    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      this.isConnected = true;
      this.triggerEvent('open'); // 触发连接成功的回调
    };

    this.socket.onmessage = (event) => {
      this.triggerEvent('message', event.data); // 触发消息接收的回调
    };

    this.socket.onerror = (error) => {
      this.triggerEvent('error', error); // 触发错误的回调
    };

    this.socket.onclose = () => {
      this.isConnected = false;
      this.triggerEvent('close'); // 触发连接关闭的回调
    };
  }

  // 发送消息
  sendMessage(message) {
    if (!this.isConnected) {
      return;
    }
    this.socket.send(message);
  }

  // 注册事件监听
  on(event, callback) {
    if (!this.eventHandlers[event]) {
      this.eventHandlers[event] = [];
    }
    this.eventHandlers[event].push(callback);
  }

  // 触发事件
  triggerEvent(event, data) {
    if (this.eventHandlers[event]) {
      this.eventHandlers[event].forEach(callback => {
        callback(data);
      });
    }
  }

  // 关闭连接
  close() {
    if (this.isConnected) {
      this.socket.close();
    }
  }
  
  // 自动重连机制
  reconnect() {
    if (this.isConnected) return;
    console.log('正在尝试重连...');
    setTimeout(() => {
      this.connect();
    }, 3000); // 3秒后重连
  }

  
}
